" -*- coding: utf-8 -*-
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"          _
"      __ | \
"     /   | /
"     \__ | \
" by Amix - http://amix.dk/
"
" Maintainer: Amir Salihefendic <amix3k at gmail.com>
" Version: 2.7
" Last Change: 12/10/06 00:09:21
" Change Log: Cyril add my mapping
"
" Sections:
" ----------------------
"   *> General "   *> Colors and Fonts
"   *> Fileformats
"   *> VIM userinterface
"   ------ *> Statusline
"   *> Visual
"   *> Moving around and tabs
"   *> General Autocommands
"   *> Parenthesis/bracket expanding
"   *> General Abbrevs
"   *> Editing mappings etc.
"   *> Command-line config
"   *> Buffer realted
"   *> Files and backups
"   *> Folding
"   *> Text options
"   ------ *> Indent
"   *> Spell checking
"   *> Plugin configuration
"   ------ *> Minibuffer
"   ------ *> Tag list (ctags) - not used
"   ------ *> VimWiki
"   ------ *> NERDTree
"   ------ *> Gundo
"   *> Filetype generic
"   ------ *> Todo
"   ------ *> VIM
"   ------ *> HTML related
"   ------ *> Ruby section
"   ------ *> Python section
"   ------ *> Cheetah section
"   ------ *> Vim section
"   ------ *> Java section
"   ------ *> JavaScript section
"   ------ *> C mappings
"   ------ *> bash
"   *> Cope
"   *> MISC
"
"  Tip:
"   If you find anything that you can't understand than do this:
"   help keyword OR helpgrep keywords
"  Example:
"   Go into command-line mode and type helpgrep nocompatible, ie.
"   :helpgrep nocompatible
"   then press <leader>c to see the results, or :botright cw
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => General
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! MySys()
    return "mac"
endfunction

"Get out of VI's compatible mode..
set nocompatible
set modifiable

"Sets how many lines of history VIM har to remember
set history=500

let loaded_matchparen = 0

"Enable filetype plugin
call pathogen#runtime_append_all_bundles()
filetype plugin on
filetype indent on

"Set to auto read when a file is changed from the outside
"set autoread

"Have the mouse enabled all the time:
set mouse=a

"Set mapleader
let mapleader = ","
let g:mapleader = ","

"Fast reloading of the .vimrc
if MySys() == "linux" || MySys() == "mac"
    map <leader>s :source ~/.vimrc<cr>
elseif MySys() == "windows"
    map <leader>s :source $VIMRUNTIME/_vimrc<cr>
endif

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Colors and Fonts
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Enable syntax hl
syntax enable
syntax on

"设置tab和空格样式
set list
set listchars=tab:\|\ ,nbsp:-,trail:-

"Set font to Monaco 10pt
if MySys() == "mac"
    "set termencoding=macroman
    set guifont=YaHei_Consolas_Hybrid:h12
    set gfn=Menlo\ Regular:h12
elseif MySys() == "linux"
    set gfn=Monospace\ 11
elseif MySys() == "windows"
"    set gfn=新宋体:h10:cGB2312
    set gfn=Consolas:h10:cANSI
endif

"switch windows size

if MySys() == "window"
  let s:isMax = 0
  function! SwWinMax()
    if s:isMax == 1
      let s:isMax = 0
    else
      let s:isMax = 1
    endif
    :call libcallnr("vimtweak.dll", "EnableMaximize", s:isMax)
  endfunction

  "toggleFullScreen
  let s:isFullScreen = 0
  function! ToggleFullScreen()
    if s:isFullScreen == 1
      let s:isFullScreen = 0
    else
      let s:isFullScreen = 1
    endif
    :call libcallnr("gvimfullscreen.dll", "ToggleFullScreen", 0)
  endfunction
endif

autocmd BufEnter * :syntax sync fromstart

if has("gui_running")
    set guioptions-=m "Remove menubar
    set guioptions-=T "Remove toolbar
"    set guioptions-=r "Remove v_scroll bar
    colorscheme  railscasts

    "setting filetype color
    if MySys() == "windows"
        map <m-F10> <ESC>:call SwWinMax()<cr>
        map <F11> <Esc>:call ToggleFullScreen()<CR>
    endif
    "set background=dark
else
    colorscheme peaksea
endif

"Highlight current
if has("gui_running")
    hi cursorline guibg=#333333
    hi CursorColumn guibg=#333333

    "autocmd InsertLeave * set nocursorline
    "autocmd InsertEnter * set cursorline

    "autocmd InsertLeave * set nocursorcolumn
    "autocmd InsertEnter * set cursorcolumn

endif

"Omni menu colors
"hi Pmenu guibg=#111111
"hi PmenuSel guibg=#775555 guifg=#ffffff

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Fileformats
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Favorite filetypes
set ffs=unix,dos
nmap <leader>fd :se ff=dos<cr>
nmap <leader>fu :se ff=unix<cr>

"autocmd BufWrite * :%s/\r//ec


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => VIM userinterface
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Set 7 lines to the curors - when moving vertical..
set so=7

"Turn on WiLd menu
set wildmenu

"Always show current position
set ruler

"The commandbar is 2 high
set cmdheight=1

"Show line number
set nu

"Do not redraw, when running macros.. lazyredraw
set lz

"Change buffer - without saving
set hid

"Set backspace
set backspace=eol,start,indent

"Bbackspace and cursor keys wrap to
set whichwrap+=<,>,h,l

"Ignore case when searching
set ignorecase
set incsearch
set nowrapscan

"Set magic on
set magic

"No sound on errors.
set noerrorbells
set novisualbell
set t_vb=

"show matching bracets
set showmatch

"How many tenths of a second to blink
set mat=2

"Highlight search things
set hlsearch

""""""""""""""""""""""""""""""
" => Statusline
""""""""""""""""""""""""""""""
"Always hide the statusline
set laststatus=2

function! CurDir()
    let curdir = substitute(getcwd(), '/Users/amir/', "~/", "g")
    return curdir
endfunction

"Format the statusline
set statusline=\ %F%m%r%h\ %w\ \ CWD:\ %r%{CurDir()}%h\ \ \ Line:\ %l/%L:%c
set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*


""""""""""""""""""""""""""""""
" => Visual
""""""""""""""""""""""""""""""
" From an idea by Michael Naumann
function! VisualSearch(direction) range
    let l:saved_reg = @"
    execute "normal! vgvy"
    let l:pattern = escape(@", '\\/.*$^~[]')
    let l:pattern = substitute(l:pattern, "\n$", "", "")
    if a:direction == 'b'
        execute "normal ?" . l:pattern . "^M"
    else
        execute "normal /" . l:pattern . "^M"
    endif
    let @/ = l:pattern
    let @" = l:saved_reg
endfunction


"Basically you press * or # to search for the current selection !! Really useful
noremap <silent> * :call VisualSearch('f')<CR>
vnoremap <silent> # :call VisualSearch('b')<CR>
exec "noremap <leader>F :%s//" . @/

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Moving around and tabs
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Map space to / and c-space to ?
"map <space> /
"map <c-space> ?

"Smart way to move btw. windows
nmap <C-j> <C-W>j
nmap <C-k> <C-W>k
nmap <C-h> <C-W>h
nmap <C-l> <C-W>l

"Actually, the tab does not switch buffers, but my arrows
"Bclose function ca be found in "Buffer related" section
"map <leader>bd :Bclose<cr>
"map <down> <leader>bd

"Use the arrows to something usefull
map <right> :bn<cr>
map <left> :bp<cr>

"Tab configuration
map <leader>tn :tabnew
map <leader>tc :tabclose<cr>
map <leader>ts :tab sball<cr>
map <S-l> :tabnext<cr>
map <S-h> :tabprevious<cr>
map <D-1> 1gt
map <D-2> 2gt
map <D-3> 3gt
map <D-4> 4gt
map <D-5> 5gt

try
    set switchbuf=usetab
    set stal=2
catch
endtry

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => General Autocommands
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Switch to current dir
map <leader>cd :cd %:p:h<cr>



" toggles the quickfix window.
command -bang -nargs=? QFix call QFixToggle(<bang>0)
function! QFixToggle(forced)
  if exists("g:qfix_win") && a:forced == 0
    cclose
  else
    execute "copen " . g:jah_Quickfix_Win_Height
  endif
endfunction

let g:jah_Quickfix_Win_Height = 10
" used to track the quickfix window
augroup QFixToggle
 autocmd!
 autocmd BufWinEnter quickfix let g:qfix_win = bufnr("$")
 autocmd BufWinLeave * if exists("g:qfix_win") && expand("<abuf>") == g:qfix_win | unlet! g:qfix_win | endif
augroup END

" toggles the quickfix window.
command! -bang -nargs=? QFix call QFixToggle(<bang>0)
function! QFixToggle(forced)
  if exists("g:qfix_win") && a:forced == 0
    cclose
  else
    execute "copen " . g:jah_Quickfix_Win_Height
  endif
endfunction

" used to track the quickfix window
augroup QFixToggle
 autocmd!
 autocmd BufWinEnter quickfix let g:qfix_win = bufnr("$")
 autocmd BufWinLeave * if exists("g:qfix_win") && expand("<abuf>") == g:qfix_win | unlet! g:qfix_win | endif
augroup END

map <F10> :QFix<cr>

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Parenthesis/bracket expanding
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"vnoremap $1 <esc>`>a)<esc>`<i(<esc>
"vnoremap $2 <esc>`>a]<esc>`<i[<esc>
"vnoremap $3 <esc>`>a}<esc>`<i{<esc>
"vnoremap $$ <esc>`>a"<esc>`<i"<esc>
"vnoremap $q <esc>`>a'<esc>`<i'<esc>
"vnoremap $w <esc>`>a"<esc>`<i"<esc>

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => General Abbrevs
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"My information
iab xdate <c-r>=strftime("%Y%m%d %H:%M:%S")<cr>
iab xname Cyril Liu

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Editing mappings etc.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

"Move a line of text using control
nmap <M-k> mz:m-2<cr>`z
nmap <M-j> mz:m+<cr>`z
vmap <M-j> :m'>+<cr>`<my`>mzgv`yo`z
vmap <M-k> :m'<-2<cr>`>my`<mzgv`yo`z

imap <M-k> <up>
imap <M-j> <down>
imap <M-h> <left>
imap <M-l> <right>

if MySys() == "mac"
    nmap <D-j> <M-j>
    nmap <D-k> <M-k>
    vmap <D-j> <M-j>
    vmap <D-k> <M-k>

    imap <D-k> <M-k>
    imap <D-j> <M-j>
    imap <D-h> <M-h>
    imap <D-l> <M-l>

endif

nmap ; g;


func! DeleteTrailingWS()
    exe "normal mz"
    %s/\s\+$//ge
    exe "normal `z"

endfunc
autocmd BufWrite *.py :call DeleteTrailingWS()
autocmd BufWrite *.rb :call DeleteTrailingWS()
autocmd BufWrite *.sh :call DeleteTrailingWS()

set completeopt=menu

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Command-line config
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
func! Cwd()
    let cwd = getcwd()
    return "e " . cwd
endfunc

func! DeleteTillSlash()
    let g:cmd = getcmdline()
    if MySys() == "linux" || MySys() == "mac"
        let g:cmd_edited = substitute(g:cmd, "\\(.*\[/\]\\).*", "\\1", "")
    else
        let g:cmd_edited = substitute(g:cmd, "\\(.*\[\\\\]\\).*", "\\1", "")
    endif
    if g:cmd == g:cmd_edited
        if MySys() == "linux" || MySys() == "mac"
            let g:cmd_edited = substitute(g:cmd, "\\(.*\[/\]\\).*/", "\\1", "")
        else
            let g:cmd_edited = substitute(g:cmd, "\\(.*\[\\\\\]\\).*\[\\\\\]", "\\1", "")
        endif
    endif
    return g:cmd_edited
endfunc

func! CurrentFileDir(cmd)
    return a:cmd . " " . expand("%:p:h") . "/"
endfunc

"Smart mappings on the command line
cno $h e ~/
cno $d e ~/Desktop/
cno $j e ./
cno $afaw cd /Users/cyril/Documents/Agree/fjnx福建农信/code/AFA_WORKSPACE/PyLib/src


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Buffer realted
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Fast open a buffer by search for a name
map <c-q> :sb

"Open a dummy buffer for paste
map <leader>q :e ~/buffer<cr>

"Restore cursor to file position in previous editing session
set viminfo='10,\"100,:20,%,n~/.viminfo
au BufReadPost * if line("'\"") > 0|if line("'\"") <= line("$")|exe("norm '\"")|else|exe "norm $"|endif|endif

" Buffer - reverse everything ... :)
map <F9> ggVGg?

" Don't close window, when deleting a buffer
command! Bclose call <SID>BufcloseCloseIt()

function! <SID>BufcloseCloseIt()
    let l:currentBufNum = bufnr("%")
    let l:alternateBufNum = bufnr("#")

    if buflisted(l:alternateBufNum)
        buffer #
    else
        bnext
    endif

    if bufnr("%") == l:currentBufNum
        new
    endif

    if buflisted(l:currentBufNum)
        execute("bdelete! ".l:currentBufNum)
    endif
endfunction

function! ClearAllOtherBuffer(noinput)
    let last_buffer = bufnr("$")
    let curr_buffer = bufnr("%")

    if a:noinput != 1 && tolower(input("删除所有buffer?[y/n] 共[". last_buffer . "]个")) != "y"
      echo "不删除就算了，我不稀罕 （︶︿︶）"
      return
    endif

    try
        for bno in range(1, last_buffer)
            execute ":bd!"
"            if (bno != curr_buffer) && (bufloaded(bno) == 1)
"                execute ": bd" bno
"            endif
        endfor
    catch
    endtry
endfunction


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Files and backups
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Turn backup off
set nobackup
set nowb
set noswapfile


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Undofile
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Turn undofile on
"set undofile
"set undodir=~/tmp/vim/undofile/


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Folding
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Enable folding, I find it very useful
set nofen
set fdl=0


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Text options
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
set expandtab
set shiftwidth=2
set tabstop=2

au FileType java,html,python,vim,javascript,ruby setl shiftwidth=2
au FileType java,html,python,vim,javascript,ruby setl tabstop=2

set smarttab
set lbr
set tw=500

""""""""""""""""""""""""""""""
" => Indent
""""""""""""""""""""""""""""""
"Auto indent
set ai

"Smart indet
set si

"C-style indeting
set cindent

"no Wrap lines
set nowrap


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Plugin configuration
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

""""""""""""""""""""""""""""""
" => syntastic
""""""""""""""""""""""""""""""
let g:syntastic_enable_signs=1
let g:syntastic_auto_loc_list=0

""""""""""""""""""""""""""""""
" => easy_grep
""""""""""""""""""""""""""""""
let g:EasyGrepRecursive=1
let g:EasyGrepJumpToMatch=0

""""""""""""""""""""""""""""""
" => fuf
""""""""""""""""""""""""""""""
nmap <down> :FufBuffer<cr>

"Note: This option must set it in .vimrc(_vimrc).  NOT IN .gvimrc(_gvimrc)!
" Disable AutoComplPop.
let g:acp_enableAtStartup = 0
" Use neocomplete.
let g:neocomplete#enable_at_startup = 1
" Use smartcase.
let g:neocomplete#enable_smart_case = 1
" Set minimum syntax keyword length.
let g:neocomplete#sources#syntax#min_keyword_length = 3
let g:neocomplete#lock_buffer_name_pattern = '\*ku\*'

" Define dictionary.
let g:neocomplete#sources#dictionary#dictionaries = {
    \ 'default' : '',
    \ 'vimshell' : $HOME.'/.vimshell_hist',
    \ 'scheme' : $HOME.'/.gosh_completions'
        \ }

" Define keyword.
if !exists('g:neocomplete#keyword_patterns')
    let g:neocomplete#keyword_patterns = {}
endif
let g:neocomplete#keyword_patterns['default'] = '\h\w*'

" Plugin key-mappings.
inoremap <expr><C-g>     neocomplete#undo_completion()
inoremap <expr><C-l>     neocomplete#complete_common_string()

" Recommended key-mappings.
" <CR>: close popup and save indent.
inoremap <silent> <CR> <C-r>=<SID>my_cr_function()<CR>
function! s:my_cr_function()
  return neocomplete#close_popup() . "\<CR>"
  " For no inserting <CR> key.
  "return pumvisible() ? neocomplete#close_popup() : "\<CR>"
endfunction
" <TAB>: completion.
inoremap <expr><TAB>  pumvisible() ? "\<C-n>" : "\<TAB>"
" <C-h>, <BS>: close popup and delete backword char.
inoremap <expr><C-h> neocomplete#smart_close_popup()."\<C-h>"
inoremap <expr><BS> neocomplete#smart_close_popup()."\<C-h>"
inoremap <expr><C-y>  neocomplete#close_popup()
inoremap <expr><C-e>  neocomplete#cancel_popup()
" Close popup by <Space>.
"inoremap <expr><Space> pumvisible() ? neocomplete#close_popup() : "\<Space>"

" For cursor moving in insert mode(Not recommended)
"inoremap <expr><Left>  neocomplete#close_popup() . "\<Left>"
"inoremap <expr><Right> neocomplete#close_popup() . "\<Right>"
"inoremap <expr><Up>    neocomplete#close_popup() . "\<Up>"
"inoremap <expr><Down>  neocomplete#close_popup() . "\<Down>"
" Or set this.
"let g:neocomplete#enable_cursor_hold_i = 1
" Or set this.
"let g:neocomplete#enable_insert_char_pre = 1

" AutoComplPop like behavior.
"let g:neocomplete#enable_auto_select = 1

" Shell like behavior(not recommended).
"set completeopt+=longest
"let g:neocomplete#enable_auto_select = 1
"let g:neocomplete#disable_auto_complete = 1
"inoremap <expr><TAB>  pumvisible() ? "\<Down>" : "\<C-x>\<C-u>"

" Enable omni completion.
autocmd FileType css setlocal omnifunc=csscomplete#CompleteCSS
autocmd FileType html,markdown setlocal omnifunc=htmlcomplete#CompleteTags
autocmd FileType javascript setlocal omnifunc=javascriptcomplete#CompleteJS
autocmd FileType python setlocal omnifunc=pythoncomplete#Complete
autocmd FileType xml setlocal omnifunc=xmlcomplete#CompleteTags

" Enable heavy omni completion.
if !exists('g:neocomplete#sources#omni#input_patterns')
  let g:neocomplete#sources#omni#input_patterns = {}
endif
"let g:neocomplete#sources#omni#input_patterns.php = '[^. \t]->\h\w*\|\h\w*::'
"let g:neocomplete#sources#omni#input_patterns.c = '[^.[:digit:] *\t]\%(\.\|->\)'
"let g:neocomplete#sources#omni#input_patterns.cpp = '[^.[:digit:] *\t]\%(\.\|->\)\|\h\w*::'

" For perlomni.vim setting.
" https://github.com/c9s/perlomni.vim
let g:neocomplete#sources#omni#input_patterns.perl = '\h\w*->\h\w*\|\h\w*::'


"                  """"""""""""""""""""""""""""""
"                  " => neocomplcache
"                  """"""""""""""""""""""""""""""
"                  " Disable AutoComplPop.
"                  let g:acp_enableAtStartup = 0
"                  " Use neocomplcache.
"                  let g:neocomplcache_enable_at_startup = 1
"                  " Use smartcase.
"                  let g:neocomplcache_enable_smart_case = 1
"                  " Use camel case completion.
"                  let g:neocomplcache_enable_camel_case_completion = 1
"                  " Use underbar completion.
"                  let g:neocomplcache_enable_underbar_completion = 1
"                  " Set minimum syntax keyword length.
"                  let g:neocomplcache_min_syntax_length = 3
"                  let g:neocomplcache_lock_buffer_name_pattern = '\*ku\*'
"                  
"                  let g:neocomplcache_enable_cursor_hold_i = 1
"                  
"                  let g:neocomplcache_disable_auto_complete = 0
"                  let g:neocomplcache_max_list = 5
"                  
"                  " Define dictionary.
"                  "let g:neocomplcache_dictionary_filetype_lists = {
"                      "\ 'default' : '',
"                      "\ 'vimshell' : $HOME.'/.vimshell_hist',
"                     "\ 'scheme' : $HOME.'/.gosh_completions'
"                      "\ }
"                  
"                  " Define keyword.
"                  "if !exists('g:neocomplcache_keyword_patterns')
"                      "let g:neocomplcache_keyword_patterns = {}
"                  "endif
"                  "let g:neocomplcache_keyword_patterns['default'] = '\h\w*'
"                  
"                  " Plugin key-mappings.
"                  imap <C-k>     <Plug>(neocomplcache_snippets_expand)
"                  inoremap <expr><C-g>     neocomplcache#undo_completion()
"                  inoremap <expr><C-l>     neocomplcache#complete_common_string()
"                  
"                  " SuperTab like snippets behavior.
"                  imap <expr><TAB> neocomplcache#sources#snippets_complete#expandable() ? "\<Plug>(neocomplcache_snippets_expand)" : pumvisible() ? "\<C-n>" : "\<TAB>"
"                  
"                  " Recommended key-mappings.
"                  " <CR>: close popup and save indent.
"                  inoremap <expr><CR>  neocomplcache#smart_close_popup() ."\<CR>"
"                  " <TAB>: completion.
"                  inoremap <expr><TAB>  pumvisible() ? "\<C-n>" : "\<TAB>"
"                  " <C-h>, <BS>: close popup and delete backword char.
"                  inoremap <expr><C-h> neocomplcache#smart_close_popup()."\<C-h>"
"                  inoremap <expr><BS> neocomplcache#smart_close_popup()."\<C-h>"
"                  inoremap <expr><C-y>  neocomplcache#close_popup()
"                  inoremap <expr><C-e>  neocomplcache#cancel_popup()
"                  
"                  " AutoComplPop like behavior.
"                  "let g:neocomplcache_enable_auto_select = 1
"                  
"                  " Enable omni completion.
"                  autocmd FileType css setlocal omnifunc=csscomplete#CompleteCSS
"                  autocmd FileType html,markdown setlocal omnifunc=htmlcomplete#CompleteTags
"                  autocmd FileType javascript setlocal omnifunc=javascriptcomplete#CompleteJS
"                  autocmd FileType python setlocal omnifunc=pythoncomplete#Complete
"                  autocmd FileType xml setlocal omnifunc=xmlcomplete#CompleteTags
"                  
"                  " Enable heavy omni completion.
"                  if !exists('g:neocomplcache_omni_patterns')
"                    let g:neocomplcache_omni_patterns = {}
"                  endif
"                  
"                  let g:neocomplcache_omni_patterns.ruby = '[^. *\t]\.\w*\|\h\w*::'
"                  autocmd FileType ruby setlocal omnifunc=rubycomplete#Complete

""""""""""""""""""""""""""""""
" => Minibuffer
""""""""""""""""""""""""""""""
let g:miniBufExplMapWindowNavVim = 1
"let g:miniBufExplMapWindowNavArrows = 1
let g:miniBufExplMapCTabSwitchBufs = 1
let g:miniBufExplModSelTarget = 1


""""""""""""""""""""""""""""""
" => Tag list (ctags) - not used
""""""""""""""""""""""""""""""
let Tlist_Ctags_Cmd = "~/bin/ctags"
let Tlist_Sort_Type = "name"
let Tlist_Show_Menu = 0
let Tlist_Use_Right_Window = 1
let Tlist_File_Fold_Auto_Close=0
let Tlist_Exit_OnlyWindow =  0
let Tlist_Show_One_File = 0
let Tlist_Auto_Open = 0
map <leader>tl :TlistToggle<cr>

""""""""""""""""""""""""""""""
" => Project
""""""""""""""""""""""""""""""
let g:proj_flags = "imst"
let g:proj_window_increment = 20
cab ppj  Project $VIMRUNTIME\project
map <F8> :Project<cr>

""""""""""""""""""""""""""""""
" => VimWiki
""""""""""""""""""""""""""""""
let wiki = {}
let apidoc = {'path': '~/code/apidoc/src', 'ext': 'page'}
let wiki.path = '~/vimwiki/'
let wiki.nested_syntaxes = {'python': 'python', 'c++': 'cpp', 'ruby': 'ruby'}
let g:vimwiki_list = [wiki, apidoc]
let g:vimwiki_CJK_length = 1

au FileType page set syntax=erubis

""""""""""""""""""""""""""""""
" => NERDTree
""""""""""""""""""""""""""""""
let NERDTreeShowBookmarks = 0
let NERDTreeQuitOnOpen = 1
map <leader>te :NERDTreeToggle %:h


""""""""""""""""""""""""""""""
" => Gundo
""""""""""""""""""""""""""""""
nnoremap <F5> :GundoToggle<CR>


""""""""""""""""""""""""""""""
" => CommandT
""""""""""""""""""""""""""""""
noremap <leader>t :CommandT<cr>
nmap <leader>e :CommandT<cr>
let g:CommandTMatchWindowAtTop = 0

""""""""""""""""""""""""""""""
" => Tabular
""""""""""""""""""""""""""""""
let g:tabular_loaded = 1

""""""""""""""""""""""""""""""
" => UltiSnips
""""""""""""""""""""""""""""""
" Trigger configuration. Do not use <tab> if you use https://github.com/Valloric/YouCompleteMe.
let g:UltiSnipsExpandTrigger="<tab>"
let g:UltiSnipsJumpForwardTrigger="<c-k>"
let g:UltiSnipsJumpBackwardTrigger="<c-j>"


" If you want :UltiSnipsEdit to split your window.
let g:UltiSnipsEditSplit="vertical"



""""""""""""""""""""""""""""""
" => Vundle
""""""""""""""""""""""""""""""
set nocompatible              " be iMproved, required
filetype off                  " required

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" alternatively, pass a path where Vundle should install plugins
"call vundle#begin('~/some/path/here')

" let Vundle manage Vundle, required
Plugin 'gmarik/Vundle.vim'

" The following are examples of different formats supported.
" Keep Plugin commands between vundle#begin/end.
" plugin on GitHub repo
"Plugin 'tpope/vim-fugitive'
" plugin from http://vim-scripts.org/vim/scripts.html
"Plugin 'L9'
" Git plugin not hosted on GitHub
"Plugin 'git://git.wincent.com/command-t.git'
" git repos on your local machine (i.e. when working on your own plugin)
"Plugin 'file:///home/gmarik/path/to/plugin'
" The sparkup vim script is in a subdirectory of this repo called vim.
" Pass the path to set the runtimepath properly.
"Plugin 'rstacruz/sparkup', {'rtp': 'vim/'}
" Avoid a name conflict with L9
"Plugin 'user/L9', {'name': 'newL9'}

Plugin 'Emmet.vim'
Plugin 'gundo'
Plugin 'SirVer/ultisnips'
Plugin 'Lokaltog/vim-easymotion'
Plugin 'godlygeek/tabular'
Plugin 'git://git.wincent.com/command-t.git'
Plugin 'Shougo/neocomplete.vim'
Plugin 'honza/vim-snippets'
Plugin 'vim-scripts/vimwiki'

" All of your Plugins must be added before the following line
call vundle#end()            " required
filetype plugin indent on    " required
" To ignore plugin indent changes, instead use:
"filetype plugin on
"
" Brief help
" :PluginList          - list configured plugins
" :PluginInstall(!)    - install (update) plugins
" :PluginSearch(!) foo - search (or refresh cache first) for foo
" :PluginClean(!)      - confirm (or auto-approve) removal of unused plugins
"
" see :h vundle for more details or wiki for FAQ
" Put your non-Plugin stuff after this line


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Filetype generic
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""


""""""""""""""""""""""""""""""
" => VIM
""""""""""""""""""""""""""""""
autocmd FileType vim map <buffer> <leader><space> :w!<cr>:source %<cr>


""""""""""""""""""""""""""""""
" => HTML related
""""""""""""""""""""""""""""""
" HTML entities - used by xml edit plugin
let xml_use_xhtml = 1
let xml_no_auto_nesting = 1

"To HTML
let html_use_css = 1
let html_number_lines = 0
let use_xhtml = 1


""""""""""""""""""""""""""""""
" => Ruby section
""""""""""""""""""""""""""""""
"tabstop
au FileType Ruby setl shiftwidth=2
au FileType Ruby setl tabstop=2

let g:LustyJugglerSuppressRubyWarning = 1

autocmd FileType ruby map <buffer> <leader><space> :w!<cr>:!ruby %<cr>
autocmd FileType ruby set makeprg=ruby\ -c\ %
"autocmd FileType ruby command Ctags !ctags -R --languages=Ruby -f __tags
autocmd FileType ruby set tags=__tags

"open ruby test window
if MySys() == "windows"
    let rb_temppath = $VIMRUNTIME . "/tmp/ruby/"
elseif MySys() == "mac" || MySys() == "mac"
    let rb_temppath = "~/study/ruby/playground/"
endif

map rb :execute ":new " . rb_temppath . "toy_" . strftime("%Y%m%d") . ".rb"<cr>


" => rails plugin settings
autocmd User Rails  silent! Rlcd
autocmd User Rails  map <buffer> <F9> :Rake<CR>

autocmd User Rails.controller*  iabbr <buffer> wsn wsdl_service_name
autocmd User Rails.model.arb*   iabbr <buffer> vfo validates_format_of
autocmd User Rails.view.erb*    imap  <buffer> <C-Z> <%=  %><C-O>3h

au FileType erubis set syntax=erubis



""""""""""""""""""""""""""""""
" => autoit section
""""""""""""""""""""""""""""""
au FileType autoit so $VIMRUNTIME/syntax/autoit.vim

""""""""""""""""""""""""""""""
" => Python section
""""""""""""""""""""""""""""""
"Run the current buffer in python - ie. on leader+space
au FileType python setl shiftwidth=4
au FileType python so $VIMRUNTIME/syntax/python.vim
autocmd FileType python map <buffer> <leader><space> :w!<cr>:!python %<cr>

"Set some bindings up for 'compile' of python
autocmd FileType python set makeprg=python\ -c\ \"import\ py_compile,sys;\ sys.stderr=sys.stdout;\ py_compile.compile(r'%')\"
"autocmd FileType python set efm=%C\ %.%#,%A\ \ File\ \"%f\"\\,\ line\ %l%.%#,%Z%[%^\ ]%\\@=%m
"autocmd FileType python set efm=%C\ %.%#,%A\ \ File\ \"%f\"\\,\ line\ %l%.%#,%Z%[%^\ ]%\\@=%m

cab afawk '/Users/cyril/Documents/Agree/fjnx福建农信/code/AFA_WORKSPACE/PyLib/src/平台'

function! InsertColon()
    let curLine = getline(line("."))
    let curCol = col(".")
    let qList = GetQuotePosList(curLine)
    let isQuoted = 0
    for i in range(len(qList))
        if qList[i] > curCol

        endif
    endfor
endfunction


cab pylint !pylint %

"Other Map

"open test window
let py_temppath = "~/study/python/playground/"
map <leader>py :execute ":new " . py_temppath . "tset_python_" . strftime("%Y%m%d") . ".py"<cr>

"Run in the Python interpreter
function! Python_Eval_VSplit() range
    let src = tempname()
    "     let dst = tempname()
    execute ": " . a:firstline . "," . a:lastline . "w " . src
    "     execute ":!python " . src . " >> " . dst
    execute ":!python " . src
    "     execute ":pedit! " . dst
endfunction
au FileType python vmap <F7> :call Python_Eval_VSplit()<cr>


""""""""""""""""""""""""""""""
" => Cheetah section
"""""""""""""""""""""""""""""""
autocmd FileType cheetah set ft=xml
autocmd FileType cheetah set syntax=cheetah

"""""""""""""""""""""""""""""""
" => Vim section
"""""""""""""""""""""""""""""""
autocmd FileType vim set nofen

"""""""""""""""""""""""""""""""
" => Java section
"""""""""""""""""""""""""""""""
"au FileType java inoremap <buffer> <C-t> System.out.println();<esc>hi

"Java comments
"autocmd FileType java source $VIMRUNTIME/macros/jcommenter.vim
"autocmd FileType java let b:jcommenter_class_author='Cyril Liu (terry6394@gmail.com)'
"autocmd FileType java let b:jcommenter_file_author='Cyril Liu (terry6394@gmail.com)'
"autocmd FileType java map <buffer> <F2> :call JCommentWriter()<cr>
autocmd FileType java set makeprg=javac\ -d\ .\ %
autocmd FileType java map <F5> <esc>:!java %:t:r<cr>
autocmd FileType java map <leader><space> :make<cr><F5>

" Only do this part when compiled with support for autocommands.
autocmd Filetype java setlocal omnifunc=javacomplete#Complete

"Abbr'z
autocmd FileType java inoremap <buffer> $pr private
autocmd FileType java inoremap <buffer> $r return
autocmd FileType java inoremap <buffer> $pu public
autocmd FileType java inoremap <buffer> $i import
autocmd FileType java inoremap <buffer> $b boolean
autocmd FileType java inoremap <buffer> $v void
autocmd FileType java inoremap <buffer> $s String

"Folding
function! JavaFold()
    setl foldmethod=syntax
    setl foldlevelstart=1
    syn region foldBraces start=/{/ end=/}/ transparent fold keepend extend
    syn match foldImports /\(\n\?import.\+;\n\)\+/ transparent fold

    function! FoldText()
        return substitute(getline(v:foldstart), '{.*', '{...}', '')
    endfunction
    setl foldtext=FoldText()
endfunction
au FileType java call JavaFold()
au FileType java setl fen

au BufEnter *.sablecc,*.scc set ft=sablecc

""""""""""""""""""""""""""""""
" => JavaScript section
"""""""""""""""""""""""""""""""
au FileType javascript so $VIMRUNTIME/syntax/javascript.vim
function! JavaScriptFold()
    setl foldmethod=syntax
    setl foldlevelstart=1
    syn region foldBraces start=/{/ end=/}/ transparent fold keepend extend

    function! FoldText()
        return substitute(getline(v:foldstart), '{.*', '{...}', '')
    endfunction
    setl foldtext=FoldText()
endfunction
au FileType javascript call JavaScriptFold()
au FileType javascript setl fen

au FileType javascript imap <c-t> console.log();<esc>hi
au FileType javascript imap <c-a> alert();<esc>hi
au FileType javascript setl nocindent
au FileType javascript inoremap <buffer> $r return

au FileType javascript inoremap <buffer> $d //<cr>//<cr>//<esc>ka<space>
au FileType javascript inoremap <buffer> $c /**<cr><space><cr>**/<esc>ka


""""""""""""""""""""""""""""""
" => HTML
"""""""""""""""""""""""""""""""
au FileType html,cheetah set ft=xml
au FileType html,cheetah set syntax=html


""""""""""""""""""""""""""""""
" => C mappings
"""""""""""""""""""""""""""""""
autocmd FileType c map <buffer> <leader><space> :w<cr>:!gcc %<cr>

""""""""""""""""""""""""""""""
" => bash
"""""""""""""""""""""""""""""""
autocmd FileType sh map <buffer> <leader><space> :w<cr>:!bash %<cr>
autocmd FileType sh map <buffer> <leader>sh :w<cr>:!bash %<cr>

let sh_temppath = "~/study/bash/playground/"
map <leader>sh :execute ":new " . sh_temppath . "test_sh" . strftime("%Y%m%d") . ".sh"<cr>

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Cope
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"For Cope
"map <silent> <leader><cr> :noh<cr>

"Orginal for all
"map <leader>n :cn<cr>
"map <leader>p :cp<cr>
"map <leader>c :botright cw 10<cr>
"map <c-u> <c-l><c-j>:q<cr>:botright cw 10<cr>


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => MISC
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Remove the Windows ^M
noremap <Leader>m<space> mmHmt:%s/<C-V><cr>//ge<cr>'tzt'm

"Remove the ending space
noremap <Leader>s<space> mmHmt:%s/\s*$//ge<cr>'tzt'm

"Paste toggle - when pasting something in, don't indent.
set pastetoggle=<F3>

"Remove indenting on empty lines
map <F2> :%s/\s*$//g<cr>:noh<cr>''

"Super paste
inoremap <C-v> <esc>:set paste<cr>mui<C-R>+<esc>mv'uV'v=:set nopaste<cr>

"A function that inserts links & anchors on a TOhtml export.
" Notice:
" Syntax used is:
"   *> Link
"   => Anchor
function! SmartTOHtml()
    TOhtml
    try
        %s/&quot;\s\+\*&gt; \(.\+\)</" <a href="#\1" style="color: cyan">\1<\/a></g
        %s/&quot;\(-\|\s\)\+\*&gt; \(.\+\)</" \&nbsp;\&nbsp; <a href="#\2" style="color: cyan;">\2<\/a></g
        %s/&quot;\s\+=&gt; \(.\+\)</" <a name="\1" style="color: #fff">\1<\/a></g
    catch
    endtry
    exe ":write!"
    exe ":bd"
endfunction

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => charset
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

" multi-encoding setting
" 该段代码要配合环境变量%LANG% = zh_CN.UTF-8 使用
if has("multi_byte")
    "set bomb
    set fileencodings=ucs-bom,utf-8,cp936,big5,euc-jp,euc-kr,latin1
    " CJK environment detection and corresponding setting
    if v:lang =~ "^zh_CN"
        " Use cp936 to support GBK, euc-cn == gb2312
        set encoding=cp936
        "set termencoding=cp936
        set fileencoding=cp936
    elseif v:lang =~ "^zh_TW"
        " cp950, big5 or euc-tw
        " Are they equal to each other?
        set encoding=big5
        "set termencoding=big5
        set fileencoding=big5
    elseif v:lang =~ "^ko"
        " Copied from someone's dotfile, untested
        set encoding=euc-kr
        "set termencoding=euc-kr
        set fileencoding=euc-kr
    elseif v:lang =~ "^ja_JP"
        " Copied from someone's dotfile, untested
        set encoding=euc-jp
        "set termencoding=euc-jp
        set fileencoding=euc-jp
    endif
    " Detect UTF-8 locale, and replace CJK setting if needed
    if v:lang =~ "utf8$" || v:lang =~ "UTF-8$"
        set encoding=utf-8
        "set termencoding=utf-8
        set fileencoding=utf-8
    endif
else
    echoerr "Sorry, this version of (g)vim was not compiled with multi_byte"
endif

"Cyril's Map
vnoremap . :normal .<CR>
map W bvw
vnoremap vw vwh

"cliboard seting
set clipboard+=unnamed " set clipboard

" Protect large files from sourcing and other overhead.
" Files become read only
if !exists("my_auto_commands_loaded")
    let my_auto_commands_loaded = 1
    " Large files are > 10M
    " Set options:
    "     eventignore+=FileType (no syntax highlighting etc
    "            assumes FileType always on)
    "       noswapfile (save copy of file)
    "       bufhidden=unload (save memory when other file is viewed)
    "       buftype=nowritefile (is read-only)
    "       undolevels=-1 (no undo possible)
    let g:LargeFile = 1024 * 1024 * 5
    augroup LargeFile
        autocmd BufReadPre * let f=expand("<afile>") | if getfsize(f) > g:LargeFile | set eventignore+=FileType | setlocal noswapfile bufhidden=unload buftype=nowrite undolevels=-1 | else | set eventignore-=FileType | endif
        augroup END
    endif

"split
noremap x "qx
noremap d "qd
noremap D "qD
noremap dd "qdd
vmap p pgvy
noremap <leader>dd dd<esc>
noremap <leader>D D
noremap <leader>x x
noremap <leader>X X

map <leader>i <esc>gR
map <C-f> :promptr<cr>
map <c-S> :browse saveas<cr>

set errorformat=%A%f:%l:\ %m,%-Z%p^,%-C%.%#

"allhtml plugin
let g:allml_global_maps = 1

filetype on
filetype plugin on

autocmd VimLeavePre * call ClearAllOtherBuffer(1)

"source $VIMRUNTIME/delmenu.vim
set langmenu=en_US.GBK
"lang message en_US
"source $VIMRUNTIME/menu.vim
map <leader>vdf <ESC>:diffthis<cr><c-w><c-w>:diffthis<cr>

"字体大小快速调整
function! AdjustFontSize(amount)
    if has("gui_running")
        let guifontli = split(&guifont, ':')
        let cursize = guifontli[1][1:]
        let newsize = cursize + a:amount
        let guifontli[1] = "h" . newsize
        let newfont = join(guifontli, ':')
        let &guifont = newfont
        echo '更新字体: ' .  newfont
    else
        echoerr "You need to run the windows version of Vim to use this function."
    endif
endfunction

function! LargerFont()
    call AdjustFontSize(2)
endfunction
command! LargerFont call LargerFont()

function! SmallerFont()
    call AdjustFontSize(-2)
endfunction
command! SmallerFont call SmallerFont()
map <c-down> :call AdjustFontSize(-1)<cr>
map <c-up> :call AdjustFontSize(1)<cr>
vmap \ :s/$/  \\/<cr>
vmap <space> :call DeleteTrailingWS() <cr>

map zk zMzX

"便捷宏定义, 便于重复上次的宏
map qq qz
nmap Q @z
"用gQ代替Q, 进入Ex模式
nnoremap gQ Q
